import 'package:flutter/services.dart';
import 'package:lib_database/lib_database.dart';
import 'package:lib_util/log/log.dart';
import 'package:lib_util/utils/utils.dart';

import '../bridge/native_channel_bridge.dart';
import '../mpc_help/createWalletTool.dart';

class ClientChannel {
  ClientChannel._privateConstructor();

  static final ClientChannel _instance = ClientChannel._privateConstructor();

  factory ClientChannel() {
    return _instance;
  }

  static const BasicMessageChannel _messageChannel =
      BasicMessageChannel('flutter._kaipay', JSONMessageCodec());

  init() {
    _messageChannel.setMessageHandler(_handleMessage);
  }

  androidUpgrade(String downloadLink, bool forceUpdate) {
    _messageChannel.send({
      'action': 'android_upgrade',
      'data': {'downloadLink': downloadLink, 'forceUpdate': forceUpdate}
    });
  }

  Future<List<Wallet>> checkAndroidOldWallet(
      {bool showNotFoundTip = false,
      bool throwErrorWhenNotFound = false}) async {
    return _messageChannel
        .send({'action': 'check_android_old_wallet'}).then((value) async {
      if (value is List) {
        if (value.isNotEmpty) {
          // EasyLoading.show(status: LocaleKeys.tongbuqianbao.tr());

          for (var v in value) {
            String key = v['key'];
            String? name = v['name'];
            Log.logger.d(
                'key:$key,mnemonic:${Utils.isMnemonic(key)},privateKey:${Utils.isPrivateKey(key)}');
            try {
              final userId =
                  NativeChannelBridge.instance.appCommMsg?.userId ?? '';
              if (Utils.isMnemonic(key) || Utils.isPrivateKey(key)) {
                await createWalletTool().createWallet(
                    key, [ChainList.ompChain], userId,
                    walletName: name);
              } else if (Utils.isEthereumAddress(key)) {
                await createWalletTool().createWatchWallet(
                    key, [ChainList.ompChain], userId,
                    walletName: name);
              } else if (Utils.isTronAddress(key)) {
                await createWalletTool().createWatchWallet(
                    key, [ChainList.tronChain], userId,
                    walletName: name);
              }
            } catch (e) {
              Config.logger.e(e);
            }
          }

          // EasyLoading.dismiss();
        } else {
          if (showNotFoundTip) {
            // EasyLoading.showError(LocaleKeys.weifaxianjiuqianbao.tr());
          }
          if (throwErrorWhenNotFound) {
            // throw LocaleKeys.weifaxianjiuqianbao.tr();
          }
        }
      }
      return Future.value(ObjectBox().walletModel.getWalletList());
    });
  }

  Future<dynamic> _handleMessage(message) async {
    Config.logger.d('flutter receive message from android:$message');
    // try {
    //   String action = message['action'];
    //   if ('android_syn_wallet_by_key' == action) {
    //     String key = message['data'];
    //     if (Utils.isMnemonic(key)) {
    //       await ObjectBox()
    //           .addWalletByHdKey(key, [ChainList.ethChain, ChainList.tronChain]);
    //       return Future.value({'success': true});
    //     } else if (Utils.isPrivateKey(key)) {
    //       await ObjectBox()
    //           .addWalletByPKey(key, [ChainList.ethChain, ChainList.tronChain]);
    //       return Future.value({'success': true});
    //     } else {
    //       return Future.value({'success': false});
    //     }
    //   }
    // } catch (e) {
    //   return Future.value({'success': false});
    // }
  }
}
